import 'package:mobile_app.core/core/domain/entities/learning_info/learning_info.dart';
import 'package:mobile_app.core/core/domain/helpers/close_current_learning_interval/helper.dart';

abstract class MaybeCloseCurrentInactiveLearningInterval {
  LearningInfo call({
    required LearningInfo learningInfo,
  });
}

class MaybeCloseCurrentInactiveLearningIntervalImpl
    implements MaybeCloseCurrentInactiveLearningInterval {
  const MaybeCloseCurrentInactiveLearningIntervalImpl({
    required CloseCurrentLearningInterval closeCurrentLearningInterval,
  }) : _closeCurrentLearningInterval = closeCurrentLearningInterval;

  final CloseCurrentLearningInterval _closeCurrentLearningInterval;

  @override
  LearningInfo call({
    required LearningInfo learningInfo,
  }) {
    final currentLearningIntervalStartTime = learningInfo.currentLearningIntervalStartTime;

    final currentLearningIntervalLastKnownActivityTime =
        learningInfo.currentLearningIntervalLastKnownActivityTime;

    if (currentLearningIntervalStartTime == null) {
      return learningInfo;
    }

    final currentTime = DateTime.now().toUtc();
    const inactivityDuration = Duration(minutes: 5);

    if (currentTime.difference(currentLearningIntervalLastKnownActivityTime!) <
        inactivityDuration) {
      return learningInfo;
    }

    if (currentLearningIntervalStartTime == currentLearningIntervalLastKnownActivityTime) {
      final updatedLearningInfo = learningInfo.copyWith(
        currentLearningIntervalStartTime: () => null,
        currentLearningIntervalLastKnownActivityTime: () => null,
      );

      return updatedLearningInfo;
    }

    final updatedLearningInfo = _closeCurrentLearningInterval(
      learningInfo: learningInfo,
      currentLearningIntervalEndTime: currentLearningIntervalLastKnownActivityTime,
    );

    return updatedLearningInfo;
  }
}
